//
//  DBBLoginVC.m
//  夺宝吧
//
//  Created by xiaocai on 15/6/18.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "DBBLoginVC.h"
#import "DBBRegistVC.h"
#import "GetPhoneVC.h"

#import "QQManager.h"
#import "SinaManager.h"
#import "WeiXinManager.h"
#import "ShoppingCarVC.h"

//用户登录url
#define LOGIN_URL @"/api/ApiUser/login"
@interface DBBLoginVC ()<UITextFieldDelegate>
{
   //背景view
    __weak IBOutlet UIView *bgView;
    //账号
    __weak IBOutlet UITextField *countLab;
    //密码
    __weak IBOutlet UITextField *pwdLab;
    //登陆按钮
    __weak IBOutlet UIButton *logBtn;
    //注册按钮
    __weak IBOutlet UIButton *registBtn;
    
    __weak IBOutlet UIImageView *iconImg;
    
    __weak IBOutlet UIButton *qqBtn;
    
    __weak IBOutlet UIButton *wxBtn;
    
    __weak IBOutlet UIButton *sinaBtn;
    
    __weak IBOutlet UIView *thirdLoginBgView;
}
@end
@implementation DBBLoginVC

+ (instancetype)shareVC{
    
    static DBBLoginVC *staticVC = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        staticVC = [[DBBLoginVC alloc]init];
    });
    
    return staticVC;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //屏蔽键盘事件
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeKeyBoard)];
    [self.view addGestureRecognizer:tap];
    countLab.delegate = self;
    pwdLab.delegate = self;
    pwdLab.secureTextEntry = YES;
    logBtn.layer.masksToBounds = YES;
    logBtn.layer.cornerRadius = 2;
    registBtn.layer.masksToBounds = YES;
    registBtn.layer.cornerRadius = 2;
    //判断用户有没有登录过，如果有则显示默认账号
    if ([UserInfo getUserCount] != nil) {
        countLab.text = [UserInfo getUserCount];
    }
    NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
    if (show_shopping.integerValue == 1)
    {
        //显示
        [thirdLoginBgView setHidden:NO];
    }else
    {
        [thirdLoginBgView setHidden:YES];
    }

}

- (void)awakeFromNib
{
    self.view.frame = CGRectMake(0,0,WYMWITH, WYMHEIGHT);
    
}
//关闭键盘
- (void)closeKeyBoard
{
      [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//登录
- (IBAction)loginBtnOnClick:(id)sender {
    if(countLab.text.length == 0)
    {
        [WYPublic showMessageWithTitle:nil Msg:@"请输入手机号或邮箱账号！"];
        return;
    }
    if (![self isCountRight:countLab.text]){
        [WYPublic showMessageWithTitle:nil Msg:@"输入账号有误（需要手机号或邮箱）！"];
        return;
    }
    if(pwdLab.text.length == 0)
    {
        [WYPublic showMessageWithTitle:nil Msg:@"请输入密码！"];
        return;
    }
    //关闭键盘
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    //启动登录请求
    [self startRequest];
}
//启动登录请求
- (void)startRequest
{
    [WYPublic addZheZhaoToWindowWithTitle:@"登录中……"];
    NSDictionary *params = @{@"account":countLab.text,@"password":pwdLab.text};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,LOGIN_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        
        [ShoppingCarVC shareShoppingCarVC].firstFlag = YES;
        
        NSNumber *ret = dic[@"ret"];
        if (ret.intValue == 0) {
            //保存用户信息
            NSDictionary *userinfo = dic[@"data"];
            //保存分享信息
            [UserInfo setShareTitle:dic[@"data"][@"share_title"] Content:dic[@"data"][@"share_content"] ShareURL:dic[@"data"][@"share_link"]];
            [UserInfo writeUserInfoWithDic:userinfo];
            //保存一键加群key
            //保存一键加群key
            [UserInfo keyForAddQQ:[WYPublic getUsefullStr:dic[@"data"][@"one_key_add_qq_group"]] Num:dic[@"data"][@"one_key_add_qq_group_num"]];
            //退出登录界面
//            [WYPublic logOrRegistSuccess];
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }else{
            [WYPublic showMessageWithTitle:nil Msg:dic[@"msg"]];
        }
        [WYPublic removeZheZhaoToWindow];
    } failedBlock:^{
        [WYPublic removeZheZhaoToWindow];
    } needLog:NO];
}
//判断用户信息是否正确
- (BOOL)isCountRight:(NSString *)candidate
{
    NSRange range = [candidate rangeOfString:@"@"];//查找子串，找不到返回NSNotFound 找到返回location和length
    
    if (range.location != NSNotFound) {
        NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        return [emailTest evaluateWithObject:candidate];
    }
    //匹配手机号码
    NSString *phoneRegex = @"1[3|4|5|7|8][0-9]\\d{4,8}";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    if (candidate.length < 11) {
        return NO;
    }
    if (![phoneTest evaluateWithObject:candidate]) {
        return NO;
    }
   
    return YES;
}
//注册
- (IBAction)registerBtnOnClick:(id)sender {
    DBBRegistVC *registVC = [[DBBRegistVC alloc]init];
//    registVC.father = self;
    
//    [self presentViewController:registVC animated:YES completion:nil];
    [self.navigationController pushViewController:registVC animated:YES];
}

//忘记密码
- (IBAction)forgetPwdbtnOnCLcik:(id)sender {
    GetPhoneVC *forget = [[GetPhoneVC alloc]init];
//    [self presentViewController:forget animated:YES completion:nil];
    [self.navigationController pushViewController:forget animated:YES];
}


//返回按钮的监听事件
- (IBAction)backBtnOnClick:(id)sender {
    //dismiss退出键盘
    [self dismissViewControllerAnimated:YES completion:nil];
    
//    [WYPublic logOrRegistSuccess];
}

- (IBAction)qqlogin:(id)sender
{
    [[QQManager sharedInstance] qqLogin];
}
- (IBAction)wxlogin:(id)sender
{
    [WeiXinManager weixinLogin];
}
- (IBAction)sinalogin:(id)sender
{
    [[SinaManager sharedInstance] sinaLogin];
}


#pragma mark -- 输入框协议函数
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.20 animations:^{
        bgView.frame = CGRectMake(bgView.frame.origin.x, -100, bgView.frame.size.width, bgView.frame.size.height);
    }];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.20 animations:^{
        bgView.frame = CGRectMake(bgView.frame.origin.x, 0, bgView.frame.size.width, bgView.frame.size.height);
    }];
}

//-(void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion{
//    [super dismissViewControllerAnimated:YES completion:completion];
//}
@end
